package com.rookie.im.learn.io.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Configurable
public class HeadersRabbitConfig implements BeanPostProcessor {

    @Bean
    public Queue headersExchangeQueueA() {
        return new Queue(RabbitMQConfig.RABBITMQ_DEMO_HEADERS_EXCHANGE_QUEUE_A, true, false, false);
    }
    @Bean
    public Queue headersExchangeQueueB() {
        return new Queue(RabbitMQConfig.RABBITMQ_DEMO_HEADERS_EXCHANGE_QUEUE_B, true, false, false);
    }

    @Bean
    public HeadersExchange rabbitmqDemoHeadersExchange() {
        return new HeadersExchange(RabbitMQConfig.RABBITMQ_DEMO_HEADERS_EXCHANGE_DEMO_NAME, true, false);
    }

    private static final Map<String, Object> map = new HashMap<>();
    static {
        map.put("key1", "java");
        map.put("key2", "rabbit");
    }
    @Bean
    public Binding bindHeadersA() {
        //队列C绑定到HeadersExchange交换机
        return BindingBuilder.bind(headersExchangeQueueA()).to(rabbitmqDemoHeadersExchange()).whereAll(map).match();
    }
    @Bean
    public Binding bindHeadersB() {
        //队列B绑定到HeadersExchange交换机
        return BindingBuilder.bind(headersExchangeQueueB()).to(rabbitmqDemoHeadersExchange()).whereAny(map).match();
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RabbitAdmin) {
            RabbitAdmin rabbitAdmin = (RabbitAdmin) bean;
            rabbitAdmin.declareExchange(rabbitmqDemoHeadersExchange());
            rabbitAdmin.declareBinding(bindHeadersA());
            rabbitAdmin.declareBinding(bindHeadersB());
        }
        return bean;
    }

}
